package com.bd.rj.backstage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bd.rj.backstage.mapper.EnterpriseMapper;
import com.bd.rj.backstage.service.IEnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.rj.common.entity.Enterprise;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 白世俊
 * @since 2025-01-03
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {
    @Resource
    EnterpriseMapper enterpriseMapper;

    @Override
    public IPage<Enterprise> getEnterpriseByPage(int pageNum, QueryWrapper<Enterprise> queryWrapper) {
        Page<Enterprise> page = new Page(pageNum, 2);
        Page<Enterprise> enterprisePage = enterpriseMapper.selectPage(page, queryWrapper);
        return enterprisePage;
    }

    @Override
    public IPage<Map<String,Object>> getEnterpriseByConditionAndPage(int pageNum,int pageSize,Enterprise enterprise) {
        Page<Map<String,Object>> page = new Page(pageNum, pageSize);
        Page<Map<String,Object>> enterpriseByCondition = enterpriseMapper.getEnterpriseByCondition(page,enterprise);
        return enterpriseByCondition;

    }

    @Override
    public void insertEnterpriseRecord(Map<String,Object> map) {
        enterpriseMapper.insertEnterpriseRecord(map);
    }

    @Override
    public List<Map<String, Object>> getIndustries() {
         return enterpriseMapper.getIndustries();
    }

    @Override
    public List<Map<String, Object>> buildHierarchy(List<Map<String, Object>> industries) {
        Map<Object, List<Map<String, Object>>> groupedByParent = industries.stream()
                .collect(Collectors.groupingBy(industry -> Optional.ofNullable(industry.get("parent")).orElse(-1)));

        // 递归构建层级结构
        return groupedByParent.getOrDefault(-1, Collections.emptyList())
                .stream()
                .map(parent -> buildNode(parent, groupedByParent))
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> buildNode(Map<String, Object> parent, Map<Object, List<Map<String, Object>>> groupedByParent) {
        Map<String, Object> node = new LinkedHashMap<>();
        node.put("label", parent.get("name"));
        List<Map<String, Object>> children = groupedByParent.getOrDefault(parent.get("id"), Collections.emptyList())
                .stream()
                .map(child -> buildNode(child, groupedByParent))
                .collect(Collectors.toList());
        if (!children.isEmpty()) {
            node.put("options", children);
        }
        return node;
    }
}
